import server from './sever'

function myserver (){
    this.server=server
    this.nowHandle=null
}
myserver.prototype.parseRouter=function(name,urlobj){
    var obj = this[name]={}
    Object.keys(urlobj).forEach(apiName=>{
        obj[apiName]=this.sendMes.bind(this,name,apiName,urlobj[apiName])
        obj[apiName].state='ready'
    })
}
myserver.prototype.v=function (vueObj) {
        this.nowHandle=vueObj//当前vue组件的this，用于自动绑定
        return this
}
myserver.prototype.sendMes=function(moduleName,apiName,url,configs){
    var config=configs || {}
    var type = config.type||'post'
    var data = config.data||{}
    if(type=="get"&&data){
        data={params:config.data}
    }
    var isAsync = config.isAsync||true//如果是false,那么意味着一个接口同一时间只能进行一次请求，不适合同一接口不同参数的同时请求
    var self = this
    // var bindname = config.bindName||apiName

    var before = function (res) {
        self[moduleName][apiName].state="ready"
        return res
    }   
    var defaultFn = function (res) {
        // self.nowHandle[bindname]=res.data
        return res
    }
    var successCallBack = config.success||defaultFn

    if(isAsync||this[moduleName][apiName].state=="ready"){
        this[moduleName][apiName].state="waitting"
        this.server[type](url,data).then(before).then(res => {
            //console.log(res)
            if(res && res.code === '0') {
                successCallBack(res)
            } else {
                if(config.error) {
                    config.error(res)
                }
            }
        }).catch(res=>{
            console.log('出错了:' + res)
            if(config.error) {
                config.error(res)
            }
        })
    }

}
export default new myserver
